package com.lzh.gulimall.product.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 *SpringCache原理：
 * CacheAutoConfiguration->RedisCacheConfiguration->
 * 自动配置了RedisCacheManager->初始化所有缓存->每个缓存决定使用什么配置
 * ->如果redisCacheConfiguration有就用已经有的，没有就用默认的
 * ->所以如果想自定义缓存配置，只需要给容器中放一个RedisCacheConfiguration，即可
 * ->就会应用到当前RedisCacheManager管理的所有缓存分区中
 *
 **/
@EnableConfigurationProperties({CacheProperties.class})
@Configuration
@EnableCaching
public class MyCacheConfig {
    /**
     * 1。原来和配置文件绑定的配置类是这样子的
     *      @ConfigurationProperties(prefix = "spring.cache")
     * 2.要让它生效，当前配置类@EnableConfigurationProperties({CacheProperties.class})，
     * 当前类开启属性配置的绑定功能
     * 3.从容器获取CacheProperties配置，就能获取到配置文件中的所有配置了
     * 4.在把配置设置上即可
     *
     * @param cacheProperties：会自动从ioc容器中获取
     * @return
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();

        //设置key,value的序列化机制
        redisCacheConfiguration = redisCacheConfiguration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        //设置配置文件中的配置
        if (redisProperties.getTimeToLive() != null) {
            redisCacheConfiguration = redisCacheConfiguration.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            redisCacheConfiguration = redisCacheConfiguration.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            redisCacheConfiguration = redisCacheConfiguration.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            redisCacheConfiguration = redisCacheConfiguration.disableKeyPrefix();
        }
        return redisCacheConfiguration;
    }

}
